<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use third\Esign;

/**
 * 合同模板
 *
 * @icon fa fa-circle-o
 */
class Template extends Backend
{

    /**
     * Template模型对象
     * @var \app\admin\model\Template
     */
    protected $model = null;
    protected $relationSearch = true;
    protected $searchFields = 'id';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Template;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function docTemplateCreate($ids)
    {

        $Esign = new Esign();

        $info = $this->model->where('id', $ids)->find();
        if ($info['esign_fileid']) {

            $fileid = $info['esign_fileid'];
        } else {
            $file_array = explode('uploads', $info['file_url']);

            $fileurl = root_path() . 'public/uploads' . $file_array[1];
            $file_path = explode('/', $fileurl);
            $fileid = $Esign->fileUploadUrl($fileurl, $file_path[count($file_path) - 1]);
            $this->model->where('id', $ids)->update(['esign_fileid' => $fileid]);
        }
        $fileStatues = $Esign->fileStatues($fileid);
        if ($fileStatues !== 2) {
            $this->error('文件上传失败，稍后操作或重新上传文件');
        }

        if ($info['docTemplateId']) {
            $result = $Esign->docTemplateEditUrl($info['docTemplateId'], '');
            if ($result['code'] != 0) {
                $this->error($result['message']);
            }
        } else {
            $result = $Esign->docTemplateCreateUrl($fileid, $info['title'], 0);
            if ($result['code'] == 0) {
                $this->model->where('id', $ids)->update(['docTemplateId' => $result['data']['docTemplateId']]);
            } else {
                $this->error($result['message']);
            }
            $result['data']['docTemplateEditUrl'] = $result['data']['docTemplateCreateUrl'];
        }

        $this->success('成功', '',$result['data']);


    }


}
